package com.gengzp.common.utils;

import com.gengzp.common.config.ThreadPoolConfig;
import com.gengzp.common.exception.BusinessException;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @ClassName ThreadUtils
 * @Description 线程工具类
 * @Author gengzp
 * @Date 2025/9/16 17:32
 */
public class ThreadUtils {

    private static final Logger logger = LoggerFactory.getLogger(ThreadUtils.class);

    private ThreadUtils() {
    }

    /**
     * 获取线程池实例
     */
    public static ThreadPoolExecutor getThreadPoolExecutor() {
        return ThreadPoolConfig.getInstance();
    }

    /**
     * 执行无返回值的任务
     *
     * @param task 要放到子线程执行的任务
     */
    public static void execute(Runnable task) {
        if (Objects.isNull(task)) {
            throw BusinessException.get("任务不能为空");
        }

        try {
            getThreadPoolExecutor().execute(task);
        } catch (Exception e) {
            logger.error("执行任务失败", e);
            throw BusinessException.get("执行任务失败");
        }
    }

    /**
     * 批量在多个线程同时执行多个任务, 并等待全部线程执行完毕
     *
     * @param tasks 要放到子线程执行的任务
     * @return 内部抛出的所有异常
     */
    public static List<String> batchExecute(Runnable... tasks) {
        List<String> errorMessages = Lists.newArrayList();
        List<CompletableFuture<Void>> futures = Lists.newArrayList();
        for (Runnable task : tasks) {
            futures.add(CompletableFuture.runAsync(() -> {
                try {
                    task.run();
                } catch (Exception e) {
                    errorMessages.add(e.getMessage());
                }
            }, getThreadPoolExecutor()));
        }
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
        return errorMessages;
    }

}
